package com.judian.smart.netty;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.judian.smart.activity.MainActivity;
import com.judian.smart.base.MyApplication;
import com.judian.smart.util.Base64;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * 设备处理响应handler
 */
@ChannelHandler.Sharable
public class DeviceChannelInboundHandler extends SimpleChannelInboundHandler<Object> {
    public static final String TAG = DeviceChannelInboundHandler.class.getSimpleName();

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg){
        if (msg instanceof String) {
            String resultStr = (String) msg;
            //if (!resultStr.contains("{") || !resultStr.contains("}")) {
            //    resultStr = Base64.decodeStr(resultStr.trim());
            //}
            Log.d("网络socket回码", resultStr);
            Intent intent = new Intent("com.zunder.smart.receiver");
            Bundle bundle = new Bundle();
            bundle.putString("str", resultStr);
            intent.putExtras(bundle);
            MyApplication.getInstance().sendBroadcast(intent);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause){
        Log.d(TAG, "exceptionCaught: 捕获到异常");
        NettySocketClient.getInstans().connectFailHandle();
        NettySocketClient.getInstans().setSocketFlag(false);
        MainActivity.getInstance().sendBroadcast(new Intent("GateWayIsLineReceiver").putExtra("gateway_connect",false));
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        super.channelUnregistered(ctx);
        Log.e("netCode", "channelUnregistered  channel 移除");
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        super.channelRegistered(ctx);
        Log.d(TAG, "channelRegistered:  channel 注册");
    }

    //客户端心跳处理
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        Log.d(TAG, "userEventTriggered: 用户事件触发");
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.READER_IDLE) {
//				logger.info("{} READER_IDLE 读超时", ctx.channel());
            } else if (event.state() == IdleState.WRITER_IDLE) {
//				logger.info("{} WRITER_IDLE 写超时", ctx.channel());
            } else if (event.state() == IdleState.ALL_IDLE) {
//				logger.info("{} ALL_IDLE 总超时", ctx.channel());
                ctx.disconnect();
            }
        } else {
            super.userEventTriggered(ctx, evt);
//			logger.info("{} userEventTriggered", ctx.channel());
        }
    }

    // Channel激活时会调用ChannelActive方法
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Log.d(TAG, "channelActive: channe 活跃");
        super.channelActive(ctx);
        NettySocketClient.getInstans().connectSucToHandle();
    }


    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        Log.d(TAG, "channelInactive: channel 不活跃");
        NettySocketClient.getInstans().connectFailHandle();
        NettySocketClient.getInstans().setSocketFlag(false);
        MainActivity.getInstance().sendBroadcast(new Intent("GateWayIsLineReceiver").putExtra("gateway_connect",false));
    }
}
